package 每日一题;

public class No415字符串相加 {

    /**
     * 给定两个字符串形式的非负整数 num1 和num2 ，计算它们的和。
     *
     * 提示：
     * num1 和num2 的长度都小于 5100
     * num1 和num2 都只包含数字 0-9
     * num1 和num2 都不包含任何前导零
     * 你不能使用任何內建 BigInteger 库， 也不能直接将输入的字符串转换为整数形式
     */

    public String addStrings(String num1, String num2) {
        //竖着相加

        num1=new StringBuilder(num1).reverse().toString();
        num2=new StringBuilder(num2).reverse().toString();
        char[] cArr1 = num1.toCharArray();
        char[] cArr2 = num2.toCharArray();
        int minLength=Math.min(cArr1.length,cArr2.length);

        StringBuilder sb=new StringBuilder();
        int carryNum=0;

        for (int i = 0; i < minLength; i++) {
            int number1=cArr1[i]-'0';
            int number2=cArr2[i]-'0';

            int sum=number1+number2+carryNum;
            int thisNum=sum%10;
            carryNum=sum/10;
            sb.append(thisNum);
        }

        if(cArr1.length>minLength){
            for (int i = minLength; i < cArr1.length; i++) {
                int sum=cArr1[i]-'0'+carryNum;
                int thisNum=sum%10;
                carryNum=sum/10;
                sb.append(thisNum);
            }
        }else if(cArr2.length>minLength){
            for (int i = minLength; i < cArr2.length; i++) {
                int sum=cArr2[i]-'0'+carryNum;
                int thisNum=sum%10;
                carryNum=sum/10;
                sb.append(thisNum);
            }
        }
        if(carryNum!=0){
            sb.append(carryNum);
        }

        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        No415字符串相加 n=new No415字符串相加();
        String result = n.addStrings("999", "1");
        System.out.println(result);
    }

}
